<?php
namespace app\admin\controller;

class Auth extends \think\Controller{

    /**
     * 初始
     */
    public function _initialize(){
        $this->view->engine->layout(false);
    }

    /**
     * 登录
     */
    public function login(){
        if(request()->isPost()){
            $params = request()->only('username,password,rememberme', 'post');
            $username = $params['username'];
            $password = $params['password'];
            $rememberme = isset($params['rememberme']) && intval($params['rememberme']) > 0 ? true : false;
            cookie('admin_username', NULL) or ($rememberme and cookie('admin_username', $username));
            $userinfo = \model\User::getByUsername($username);
            if(empty($userinfo)) $userinfo = \model\User::getByMobile($username);
            if(empty($userinfo)) $userinfo = \model\User::getByEmail($username);
            empty($userinfo) and $this->result(false, 1001, '获取用户失败', 'json');
            // do more ....
            \model\User::where('id', $userinfo->id)->update([
                'last_login_time' => time(),
                'login_times' => $userinfo->login_times + 1
            ]);
            cache('admin_auth_ticket', encrypt((string)$userinfo, '', 7200));
            $this->result(false, 1000, '登录成功', 'json');
        }
        cache('admin_auth_ticket', NULL);
        return $this->fetch();
    }

    /**
     * 登出
     */
    public function logout(){
        cache('admin_auth_ticket', NULL);
        $this->redirect('auth/login');
    }

    /**
     * 密码找回
     */
    public function forget(){
        if(request()->isPost()){
            $this->result(false, 1000, '提交成功', 'json');
        }
        return $this->fetch();
    }

    /**
     * 注册
     */
    public function regist(){
        if(request()->isPost()){
            $params = request()->only('username,password,mobile,email', 'post');
            $username = $params['username'];
            $mobile = $params['mobile'];
            $email = $params['email'];
            $regist_ip = get_client_ip();
            $password = md5($params['password'] . config('salt'));
            $user = \model\User::create(compact('username', 'mobile', 'email', 'password', 'regist_ip'));
            empty($user) and $this->result(false, 1001, '注册失败');
            // do more ....
            $this->result(false, 1000, '注册成功');
        }
        return $this->fetch();
    }

    /**
     * 入驻
     */
    public function settle(){
        if(request()->isPost()){
            $params = request()->only('username,password,mobile,email', 'post');
            // do more ....
            $this->result(false, 1000, '入驻成功');
        }
        return $this->fetch();
    }
}